package cn.edu.jsu.zjj.controller;


import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.common.DeleteRequest;
import cn.edu.jsu.zjj.common.result.PageResult;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.exception.ThrowUtils;
import cn.edu.jsu.zjj.model.dto.major.MajorAddMyRequest;
import cn.edu.jsu.zjj.model.dto.major.MajorQueryRequest;
import cn.edu.jsu.zjj.model.dto.major.MajorUpdateMyRequest;
import cn.edu.jsu.zjj.model.entity.Major;
import cn.edu.jsu.zjj.service.MajorService;
import cn.edu.jsu.zjj.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.Month;
import java.util.List;

/**
 * 专业相关接口
 */
@RestController
@RequestMapping("/major")
@Slf4j
@Api(tags = "专业管理接口")
public class MajorController {
    @Autowired
    private MajorService majorService;

    @ApiOperation("专业分页查询")
    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody MajorQueryRequest majorQueryRequest) {
        log.info("专业分页查询，参数为：{}", majorQueryRequest);
        long current = majorQueryRequest.getCurrent();
        long size = majorQueryRequest.getPageSize();
        Page<Major> majorPage = majorService.page(new Page<>(current, size),
                majorService.getQueryWrapper(majorQueryRequest));
        return Result.success(new PageResult(majorPage.getTotal(), majorPage.getRecords()));
    }

    @ApiOperation("专业全部查询")
    @PostMapping("/list")
    public Result list() {
        LambdaQueryWrapper<Major> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Major::getCreateTime);
        List<Major> majorList = majorService.list(queryWrapper);
        return Result.success(majorList);
    }


    /**
     * 新增专业
     *
     * @param majorAddMyRequest
     * @return
     */
    @Type("新增专业")
    @ApiOperation("新增专业（仅管理员）")
    @PostMapping
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result save(@RequestBody MajorAddMyRequest majorAddMyRequest) {
        log.info("新增专业：{}", majorAddMyRequest);
        Major major = new Major();
        BeanUtils.copyProperties(majorAddMyRequest, major);
        major.setType(majorAddMyRequest.getType());
        Long parentId = majorAddMyRequest.getParentId();
        if (parentId != null && parentId != 0) {
            Major parent = majorService.getById(parentId);
            major.setTreePath(parent.getTreePath() + "-" + majorAddMyRequest.getParentId());
        }
        boolean result = majorService.save(major);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }

    /**
     * 编辑专业信息
     * @param majorUpdateMyRequest
     * @return
     */
    @Type("编辑专业信息")
    @ApiOperation("编辑专业信息")
    @PutMapping
    public Result<String> update(@RequestBody MajorUpdateMyRequest majorUpdateMyRequest) {
        log.info("编辑专业，请求体为：{}", majorUpdateMyRequest);
        if (majorUpdateMyRequest == null) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        Major major = new Major();
        BeanUtils.copyProperties(majorUpdateMyRequest, major);
        major.setType(majorUpdateMyRequest.getType());
        Major parentMajor = majorService.getById(majorUpdateMyRequest.getParentId());
        major.setTreePath(parentMajor.getTreePath() + "-" + major.getParentId());
        major.setTreePath(parentMajor.getTreePath() + "-" + major.getParentId());
        boolean result = majorService.updateById(major);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success("更新成功");
    }


    @Type("删除专业")
    @PostMapping("/delete")
    @ApiOperation("删除专业（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<Boolean> deleteMajor(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        return Result.success(majorService.removeById(deleteRequest.getId()));
    }

    /**
     * 根据id查询专业,并且去掉isDelete=1的记录
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询专业")
    @GetMapping("/{id}")
    public Result<Major> getById(@PathVariable Long id) {
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        Major major = majorService.getById(id);
        log.info("查询专业，结果为：{}", major);
        ThrowUtils.throwIf(major == null, MessageConstant.NOT_FOUND_ERROR);
        return Result.success(major);
    }
}
